package com.advert.presentation.util;

import com.advert.config.Config;
import com.advert.service.util.ImageProcessingService;
import org.jboss.seam.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageCacheFilter implements Filter {
    private ServletContext servletContext;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.servletContext = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String requestUri = ((HttpServletRequest)servletRequest).getRequestURI();
        if (!imageExist(requestUri)) {
            Config config = (Config)Component.getInstance("config");
            File directory = new File(servletContext.getRealPath(config.getImageConfig().getUploadedUri()));
            ((ImageProcessingService)Component.getInstance("ImageProcessingService")).cacheImagesOnDisk(extractImageId(requestUri), directory);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }

    private boolean imageExist(String uri) {
        File f = new File(servletContext.getRealPath(uri));
        return f.exists();
    }

    private Integer extractImageId(String uri) {
        Integer retVal = null;
        String[] tokens = uri.split("/");
        if (tokens.length != 0) {
            String fileName = tokens[tokens.length - 1];
            tokens = fileName.split("_|\\.");
            if (tokens.length != 0) {
                String id = tokens[0];
                try {
                    retVal = Integer.parseInt(id);
                } catch (NumberFormatException e) {}
            }
        }
        return retVal;
    }
}
